
var	userAgent = window.navigator.userAgent.toLowerCase(),
	appVersion = window.navigator.appVersion.toLowerCase(),
	ieVersion;
if ((userAgent.indexOf("msie") != -1) || (userAgent.indexOf("trident") != -1) ) {
	ieVersion = true;
	var res = userAgent.match(/(msie|rv).([\d\.]+)/);
	ieVersion= RegExp.$2 || '';
}

(function($){
	$.fn.copyBlock = function(){
		if($(this).length <= 0){ return; };
		$(this).attr("unselectable","on").css({"user-select":"none", "-moz-user-select":"none", "-webkit-user-select":"none", "-ms-user-select":"none"});
		$("body").on("copy selectstart mousedown contextmenu",function(e){e.preventDefault();});
	};

	$.fn.scrollTo = function(){
		var	offset = $(this).offset();
		$('html,body').animate({ scrollTop: offset.top }, 'fast');
	};

	$.fn.targetToggle = function(className, callback){
		var	className = className || "_open";
		$(this).each(function(){
			var	selfNode = $(this);
			var	targetSelector = selfNode.data("target") || this;
			selfNode.on("click",function(e){
				e.preventDefault();
				$(targetSelector).toggleClass(className);
				if(typeof(callback) == "function"){
					callback(this);
				};
			});
		});
	};
	$.fn.setToggle = function(className, callback){
		var	className = className || "_setToggleOn";
		$(this).each(function(){
			var	nodeIndex = {
					self : $(this),
					item : $(this).find("._setToggleItem")
				};
			nodeIndex.item.each(function(){
				var	thisItem = $(this);
				$(this).find("._setToggleSwich").on("click",function(e){
					e.preventDefault();
					if(thisItem.hasClass(className)){
						thisItem.removeClass(className);
					}else{
						nodeIndex.item.removeClass(className);
						thisItem.addClass(className).scrollTo();
					}
					if(typeof(callback) == "function"){
						callback(this);
					};
				});
			});
		});
	};

	$.fn._addInput = function(){
		$(this).each(function(){
			var targetname = $(this).data("targetname");
			var nodeIndex = {
					area : $(this),
					input :  $(this).find("[name="+targetname+"]")
				};
			nodeIndex.input.each(function(){
				var self = $(this);
				if(self.is(':checked')){
					self.closest("._addInput_unit").addClass("_on");
				}else{
					self.closest("._addInput_unit").find("._addInput_item").find("input").attr("disabled","disabled");
					self.closest("._addInput_unit").find("._addInput_item").find("select").attr("disabled","disabled");
				}
				self.on("change",function(){
					nodeIndex.area.find("._addInput_unit").removeClass("_on");
					nodeIndex.area.find("._addInput_item").find("input").attr("disabled","disabled");
					nodeIndex.area.find("._addInput_item").find("select").attr("disabled","disabled");
					if(self.is(':checked')){
						self.closest("._addInput_unit").addClass("_on");
						self.closest("._addInput_unit").find("._addInput_item").find("input").removeAttr("disabled");
						self.closest("._addInput_unit").find("._addInput_item").find("select").removeAttr("disabled");
					}
				});
			});
		});
	};

	/*
		対象要素に「_ga」クラスをあてる。イベント情報はdata属性で管理。
		data-gaParam: ページ名など
		data-gaName: 枠名など
		data-gaExclude: hrefが「#、空、javascript:void(0)」の場合除外

		例：
		<div class="_ga" data-gaParam="param1" data-gaName="name1" data-gaExclude="true">
			<a href="#">計測対象外</a>
			<a href="women">計測対象</a>
		</div>
	*/
	$.fn._gaEventPush = function() {
		var $ele = this;
		$ele.each(function() {
			var
				 $self = $(this)
				,param = $self.data('gaparam')
				,gaName = $self.data('ganame')
				,gaEx = $self.data('gaexclude')
			;
			var _gaPush = function() {
				dataLayer.push({
					 event: "trackEvent"
					,eventName:param
					,eventAction:gaName
				});
			};
			$self.find('a').each(function(){
				$(this).on("click", function(e){
					var href = $(this).attr('href');
					if (gaEx) {
						// ページ遷移以外のhrefは除外する
						if(href.match(/^#/) || href == '' || href == 'javascript:void(0)') {
							return;
						} else {
							// dataLayerでgaに飛ばす
							_gaPush();
						}
					} else {
						// dataLayerでgaに飛ばす
						_gaPush();
					}
				});
			});
		});
		return this;
	};

})(jQuery);

$(function(){
	var	addFigure = function(str) { var num = new String(str).replace(/,/g, ""); while(num != (num = num.replace(/^(-?\d+)(\d{3})/, "$1,$2"))); return num; };

	(function(area){
		if(area.length <= 0){
			return;
		};
		var	className = {
				priceArea : "_priceArea",
				sale : "_sale",
				price : "_price",
				viewPrice : "_viewPrice",
				pointArea : "_pointArea",
				pointUp : "_pointup",
				point : "_point",
				newPoint : "_newPoint",
				delivery : "_delivery",
				form : "_form",
				choice : "_choice",
				child : "_child",
				selectedName : "_selectedName",
				attention : "_attention",
				choicedCount : "_choicedCount",
				totalCount : "_totalCount",
				statusList : "_statusList",
				stock : "_stock",
				stockStatus : "_stockStatus",
				allStockStatus : "_speed _normal _reserv",
				buttonArea : "_buttonArea",
				disable : "_disable"
			};
		var	nodeIndex = {
				area : area,
				priceArea : area.find("."+className.priceArea),
				price : area.find("."+className.price),
				viewPrice : area.find("."+className.viewPrice),
				pointArea : area.find("."+className.pointArea),
				point : area.find("."+className.point),
				newPoint : area.find("."+className.newPoint),
				delivery : area.find("."+className.delivery),
				form : area.find("."+className.form),
				choice : area.find("."+className.choice),
				child : area.find("."+className.child),
				choicedCount : area.find("."+className.choicedCount),
				totalCount : area.find("."+className.totalCount),
				statusList : area.find("."+className.statusList),
				stock : area.find("."+className.stock),
				stockStatus : area.find("."+className.stockStatus),
				buttonArea : area.find("."+className.buttonArea)
			},
			defStatus = "null",
			choiced = "choiced",
			passed = "passed",
			stockStatusClass = "",
			checkSelector = "",
			fireObj;
		if(nodeIndex.choice.size() >= 1){
			if(nodeIndex.choice[0].tagName == "OPTION"){
				checkSelector = ":selected";
				fireObj = nodeIndex.choice.closest("select");
			}else{
				checkSelector = ":checked";
				fireObj = nodeIndex.choice;
			}
		}
		var	deliveryFree = nodeIndex.area.data("borderDelifree"),
			deliveryStatus = nodeIndex.delivery.data("status");
		function deliUpdate(type,amount,quantity,condition){
			var deliTxt = "";
			if(type == "1"){
				deliTxt = "全品送料無料です";
			}else if(type == "2"){
				deliTxt = "ただいま送料無料です";
			}else if(type == "3"){
				deliTxt = "初回購入者限定、全品送料無料です";
			}else if(type == "4"){
				if(condition-amount > 0){
					deliTxt = "あと"+addFigure(condition-amount)+"円で送料無料です";
				}else{
					deliTxt = "送料無料になりました";
				}
			}else if(type == "5"){
				if(condition-amount > 0){
					deliTxt = "あと"+addFigure(condition-quantity)+"個で送料無料です";
				}else{
					deliTxt = "送料無料になりました";
				}
			}
			return deliTxt;
		};
		function update(){
			var	price = 0,
				priceView = 0,
				point = 0,
				pointUped = 0,
				cost = 0,
				stocktime = 0,
				stocktext = "",
				stockstatus = "",
				cnt = 0,
				errCnt = 0;
			nodeIndex.child.each(function(){
				var self = $(this);
				if(self.data("status") == choiced){
					cnt++;
					point += self.data("point");
					if(self.data("priceView") > self.data("priceWidthtax")){
						priceView += self.data("priceView");
					}else{
						priceView += self.data("priceWidthtax");
					};
					if(self.data("upedPoint") > self.data("point")){
						pointUped += self.data("upedPoint");
					}else{
						pointUped += self.data("point");
					};
					price += self.data("priceWidthtax");
					var choicedObj = self.find("."+className.choice+checkSelector);
					if(choicedObj.data("stockTime") >= stocktime){
						stocktime = choicedObj.data("stockTime");
						stocktext = choicedObj.data("stockText");
						stockstatus = choicedObj.data("stockStatus");
					};
					self.find("._childStock").text(choicedObj.data("stockText"));
					self.find("._childStockStatus").removeClass(className.allStockStatus).addClass(choicedObj.data("stockStatus"));
				}else if(self.data("status")+"" == defStatus){
					errCnt++;
				};
			});
			if(priceView > price){
				nodeIndex.priceArea.addClass(className.sale);
			}else{
				nodeIndex.priceArea.removeClass(className.sale);
			};
			if(pointUped > point){
				nodeIndex.pointArea.addClass(className.pointUp);
			}else{
				nodeIndex.pointArea.removeClass(className.pointUp);
			};
			nodeIndex.price.text(addFigure(price));
			nodeIndex.viewPrice.text(addFigure(priceView));
			nodeIndex.point.text(addFigure(point));
			nodeIndex.newPoint.text(addFigure(pointUped));
			nodeIndex.choicedCount.text(cnt);
			nodeIndex.totalCount.text(errCnt);
			nodeIndex.stock.text(stocktext);
			nodeIndex.stockStatus.removeClass(className.allStockStatus).addClass(stockstatus);
			nodeIndex.delivery.text(deliUpdate(nodeIndex.delivery.data("type"),price,cnt,nodeIndex.delivery.data("condition")));
			if(price == 0){
				nodeIndex.buttonArea.addClass(className.disable);
			}else{
				nodeIndex.buttonArea.removeClass(className.disable);
			};
		};
		function choice(no,status,stockClass){
			var childClass = "_"+status;
			if(stockClass){
				childClass += " "+stockClass;
			}
			nodeIndex.area.find("."+className.child+"[data-no='"+no+"']").data("status",status).removeClass("_"+choiced+" _"+passed+" _"+defStatus+" "+className.allStockStatus+" "+className.attention).addClass(childClass);
			nodeIndex.statusList.find("*[data-no='"+no+"']").removeClass("_"+choiced+" _"+passed+" _"+defStatus).addClass("_"+status);
			update();
		};
		function attention(no){
			nodeIndex.area.find("."+className.child+"[data-no='"+no+"']").scrollTo();
		};
		if(fireObj){
			fireObj.on("change",function(){
				var	parent = $(this).closest("."+className.child);
				var	choicedObj = parent.find("."+className.choice+checkSelector);
				var	no = parent.data("no"),
					status = passed;
				if(choicedObj.val() == ""){
					status = defStatus;
				}else if(choicedObj.val() == 0){
					status = passed;
				}else{
					status = choiced;
					parent.removeClass(className.attention);
				};
				parent.find("."+className.selectedName).text(choicedObj.data("name"));
				choice(no,status,choicedObj.data("stockStatus"));
			});
		}
		nodeIndex.form.on("submit",function(e){
			var errorFirst;
			nodeIndex.area.find("."+className.child).each(function(){
				if($(this).data("status")+"" == defStatus){
					$(this).addClass(className.attention);
					if(!errorFirst){
						errorFirst = $(this);
					}
				}
			});
			if(errorFirst){
				e.preventDefault();
				attention(errorFirst.data("no"));
			};
		});
	})($('#coordinateProduct'));

	$("._copyblock").copyBlock();
	$("body._imgProtect").on("mousedown contextmenu selectstart","img",function(e){
		e.preventDefault();
	});

	$("._ga")._gaEventPush();

	$.pageGet = function(href, success_func, error_func, timeout_func){
		var	p = {
			method: "GET",
			url: href,
			res_type: "html",
			callback_success: success_func,
			callback_error: error_func,
			callback_timeout: timeout_func
		};

		$.ajaxRequest(p);
	};

	$.ajaxSetup({
		timeout: 100000
	});
	$.ajaxRequest = function(p){
		$.ajax({
			type: p.method,
			url: p.url,
			dataType: p.res_type,
			data: p.data,
			cache: (p.cache) ? p.cache : false,
			async: (p.async) ? p.async : true,
			ifModified: (p.ifModified) ? p.ifModified : false,
			beforeSend: function(xhr){
				if($.isFunction(p.beforesend_func)){
					p.beforesend_func(xhr);
				}
			},
			success: function(d){
				if($.isFunction(p.callback_success)){
					p.callback_success(d);
				}
			},
			error: function(jqXHR, textStatus, errorThrown){
				if(textStatus == "timeout"){
					if($.isFunction(p.callback_timeout)){
						p.callback_timeout();
					}
				}else{
					if($.isFunction(p.callback_error)){
						p.callback_error();
					}
				}
			},
			complete: function(){
				if($.isFunction(p.callback_complete)){
					p.callback_complete();
				}
			}
		});
	};

	//twitterCoupon
	(function(button){
		if(button.length <= 0) return;
		var	redirectUrl = "";
		if(ieVersion){
			button.each(function(){
				$(this).parent().hover(function(){
					$(this).addClass("_hover");
				},function(){
					$(this).removeClass("_hover");
				});
			});
		}else{
			button.each(function(){
				$(this).on("click",function(e){
					e.preventDefault();
					redirectUrl = "/svc/coupon/ShopCouponGet/?coupon_param="+$(this).data("param")+"&transitionToken="+$(this).data("token");
					_gaq.push(['_trackEvent','tweetCouponGet','linkClick',location.href]);
					var t = "scrollbars=yes,resizable=yes,toolbar=no,location=yes", n = 550, r = 420, i = screen.height, s = screen.width, o = Math.round(s / 2 - n / 2), u = 0, url ="https://twitter.com/intent/tweet?original_referer="+location.href+"&text="+$(this).data("text")+"&tw_p=tweetbutton&url=";
					return i > r && (u = Math.round(i / 2 - r / 2)),window.open(url, null, t + ",width=" + n + ",height=" + r + ",left=" + o + ",top=" + u),redirectUrl;
				});
			});
		}
		function redirect(event){
			if(ieVersion) return false;
			if(!event.origin) return false;
			if(/https:\/\/twitter.com/.test(event.origin)){
				if(event.data == "__ready__") return false;
				try{
					var res = $.parseJSON(event.data);
					if(res.params.indexOf("tweet") !== -1){
						var callbackFunction = function(){
							location.href = redirectUrl;
						};
						if(window._gat){
							_gaq.push(['_set','hitCallback',callbackFunction]);
							_gaq.push(['_trackEvent','tweetEnd','linkClick',location.href]);
						}else{
							callbackFunction();
						}
					}
				}catch(e){
					return false;
				}
			}
		};
		if(document.addEventListener){
			window.addEventListener("message",redirect, false);
		}else if(document.attachEvent){
			window.attachEvent("onmessage",redirect)
		}
	})($('.tweetWindowOpen'));

});